#!/usr/bin/env python
# Create: 2019/5/7
__author__ = '749B'

"""
通过 EventID 来控制事件的时间范围
通过 NetObjectType 来限制事件的类型，N 是设备的事件，I 是端口的事件
"""

import requests
from orionsdk import SwisClient

from sds import settings

# settings.npm_server = "172.16.130.2"  # 如果且内网使用的话
# 时间范围：5/24 15:05 到 5/24 15:49
start_EventID = 14641865
stop_EventID = 14644933

TOP_NUM = 100  # 每次请求的数量

npm_server = settings.npm_server
username = settings.username
password = settings.password
swis = SwisClient(npm_server, username, password)

nodes_seen = dict()
interfaces_seen = dict()

CSV_KEYS = ["EventID", "EventTime", "EngineID", "EventType", "Message", "NetObjectType",
            "NodeName", "IPAddress", "LastBoot", "PollIntervalN", "City", "Department", "CommentsN",
            "InterfaceName", "InterfaceAlias", "PollIntervalI", "CommentsI"]

requests.packages.urllib3.disable_warnings()


def get_events(start_id):
    # results = swis.query("SELECT TOP %d Uri FROM Orion.Events "
    #                      "WHERE NetObjectType IN ('I', 'N') "
    #                      "AND EventID > @startID "
    #                      "ORDER BY EventID" % TOP_NUM,
    #                      startID=start_id)
    results = swis.query("SELECT TOP %d Uri FROM Orion.Events "
                         "WHERE EventType IN (1, 10, 5000) "
                         "AND EventID > @startID "
                         "ORDER BY EventID" % TOP_NUM,
                         startID=start_id)
    for result in results['results']:
        uri = result['Uri']
        obj = swis.read(uri)
        """obj里所有的值
        这个是Node的信息:
        EventID: 14569404
        EventTime: 2019-04-29T04:31:46.77
        NetworkNode: 997
        NetObjectID: 997
        NetObjectValue: None
        EngineID: 11
        EventType: 1
        Message: Guangzhou_IPsec has stopped responding (Request Timed Out)
        Acknowledged: False
        NetObjectType: N
        TimeStamp: AAAAAfwPF7E=
        DisplayName: None
        Description: None
        InstanceType: Orion.Events
        Uri: swis://SOLARWINDSS.idx.shuxun.net/Orion/Orion.Events/EventID=14569404
        InstanceSiteId: 0
        
        下面是Interface的信息:
        EventID: 14569368
        EventTime: 2019-04-29T04:01:39.087
        NetworkNode: 256
        NetObjectID: 12617
        NetObjectValue: None
        EngineID: 13
        EventType: 10
        Message: S-3560-27(ZJJT) - FastEthernet0/16 · ZhangJiangWenHua-2M-KT100874 Down
        Acknowledged: False
        NetObjectType: I
        TimeStamp: AAAAAfwPAS0=
        DisplayName: None
        Description: None
        InstanceType: Orion.Events
        Uri: swis://SOLARWINDSS.idx.shuxun.net/Orion/Orion.Events/EventID=14569368
        InstanceSiteId: 0
        """
        yield obj


def get_info(obj):
    if obj['NetObjectType'] == "I":
        return interface_info(obj)
    if obj['NetObjectType'] == "N":
        return node_info(obj)
    print("\rEventID: %d NetObjectType 不在预计的范围内: %s" % (obj['EventID'], obj['NetObjectType']))


def node_info(obj):
    nid = obj['NetworkNode']
    if nid in nodes_seen:
        res = nodes_seen[nid]
        obj.update(res)
        return obj

    results = swis.query(
        "SELECT n.Caption AS NodeName, n.IPAddress, n.LastBoot, n.PollInterval AS PollIntervalN, "
        "c.City, c.Department, c.Comments AS CommentsN "
        "FROM Orion.Nodes n "
        "JOIN Orion.NodesCustomProperties c ON n.NodeID = c.NodeID "
        "WHERE n.NodeID=@nid", nid=nid)
    if len(results['results']) == 0:
        print("\r NodeID %d: 未查询到任何节点" % nid)
        return
    elif len(results['results']) > 1:
        print("\r NodeID %d: 查询到多个节点" % nid)
    res = results['results'][0]
    nodes_seen[nid] = res
    obj.update(res)
    return obj


def interface_info(obj):
    iid = obj['NetObjectID']
    if iid in interfaces_seen:
        res = interfaces_seen[iid]
        obj.update(res)
        return node_info(obj)

    results = swis.query(
        "SELECT i.InterfaceName, i.InterfaceAlias, i.PollInterval AS PollIntervalI, c.Comments AS CommentsI "
        "FROM Orion.NPM.Interfaces i "
        "JOIN Orion.NPM.InterfacesCustomProperties c ON i.InterfaceID = c.InterfaceID "
        "WHERE i.InterfaceID=@iid", iid=iid)
    if len(results['results']) == 0:
        print("\rInterfaceID %d: 未查询到任何节点" % iid)
        return
    elif len(results['results']) > 1:
        print("\rInterfaceID %d: 查询到多个节点" % iid)
    res = results['results'][0]
    interfaces_seen[iid] = res
    obj.update(res)
    return node_info(obj)


if __name__ == '__main__':
    import time
    start_event_id = start_EventID
    file = open('events20190524_3.csv', 'w', encoding='utf-8')
    file.write(','.join(CSV_KEYS) + '\n')

    count = 0
    start = time.time()
    current_event_id = None
    while start_event_id <= stop_EventID:
        for event_obj in get_events(start_event_id):
            current_event_id = event_obj['EventID']
            count += 1
            print("\r进度: %d/%d\t用时: %.2f秒\t已处理: %d" % (
                event_obj['EventID'], stop_EventID, time.time()-start, count), end="")
            data = get_info(event_obj)
            file.write("%s\n" % ','.join([str(data.get(key)).replace(',', '，') for key in CSV_KEYS]))
        start_event_id = current_event_id

    file.close()




